package model{
	
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.ArrayCollection;
	
	public class FoodXMLLoader extends EventDispatcher{
		
		private var urlLoader:URLLoader;
		private var xml:XML;
		private var item:DataObject;
		private var collectionData:ArrayCollection;
		private var collectionFirstFifteen:ArrayCollection;
		private var i:int;
		private var loadLimit:int;
		private var toolbox:ToolBox;
		
		public function FoodXMLLoader(url:String, loadLimit:int):void{
			
			collectionData = new ArrayCollection();
			collectionFirstFifteen = new ArrayCollection();
			toolbox = new ToolBox();
			
			urlLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, onComplete);											
			urlLoader.load(new URLRequest(url));
			this.loadLimit = loadLimit;
		}
		
		private function onComplete(e:Event):void
		{
			xml = new XML(e.target.data);
			
			for each(var obj:XML in xml.poi)
			{
				item = new DataObject();
				item.name = obj.name;
				item.id = obj.pid;
				item.desc = obj.desc;
				item.distance = obj.distance;
				item.location = obj.location;				
				item.cuisine = obj.cuisine;
				item.dining_style = obj.dining_style;
				item.price = obj.price;
				item.recommended_food = obj.recommended_food;
				item.tel = obj.tel;
				item.url = obj.url;
				item.wap_url = obj.wap_url;
				item.icon_url = obj.icon_url;
				
				for each(var posItem:XML in obj.pos)
				{
					item.state = posItem.state;
					item.city = posItem.city;
					item.addr = posItem.addr;					
					item.xLoc = posItem.x;
					item.yLoc = posItem.y;
					item.distance = toolbox.formatDistance(posItem.distance);
				}
				
				for each(var feedbackStat:XML in obj.feedback_stat.rating_stat)
				{
					item.rate_up = feedbackStat.up;
					item.rate_down = feedbackStat.down;
				}
				
				for each(var commentStat:XML in obj.feedback_stat.comment_stat)
				{
					item.review = commentStat.byuser;
				}
				
				collectionData.addItem(item);
				
				if(i<loadLimit){
					collectionFirstFifteen.addItem(item);
					i++;
				}
			}
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
	
		public function getLoadLimit():int
		{
			return loadLimit;
		}
		
		public function getCollectionData():ArrayCollection
		{
			return collectionData;
		}
		
		public function getCollectionLimit():ArrayCollection
		{
			return collectionFirstFifteen;
		}
		
	}
	
}